import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {UsedStorePService} from '../../used-store-p.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {PermissionService} from '../../../../service/permission.service';
import {purchaseChannelLists} from 'src/app/main/love-recyc-manage/machine-inspection-items';
import {CommonService} from 'src/app/services-common/common.service';
import {DatePipe} from '@angular/common';
import {NzImageService} from 'ng-zorro-antd/image';

@Component({
  selector: 'app-commodity-info',
  templateUrl: './commodity-info.component.html',
  styleUrls: ['./commodity-info.component.scss'],
  providers: [DatePipe]
})
export class CommodityInfoComponent implements OnInit {
  formData: any = {
    title: '', // 商品名称
    name: '', // 短名称
    userType: 0,
    shopPriceB: 0,
    shopPriceC: 0,
    imgs: [],
    qualityResult: '',
    asImg: '',
    renewalFlag: 0,

    color: '', // 机器信息-颜色
    network: '', // 机器信息-网络制式
    version: '', // 机器信息-版本
    isPrivateRepair: '', // 机器信息-私修痕迹 0无 1有
    guaranteeTime: '', // 机器信息-保修截止日期
    batteryHealth: '', // 机器信息-电池健康值
    chargeCount: '', // 机器信息-充电次数
    imei: '', // 机器信息-IMEI
    screenSize: '', // 机器信息-屏幕尺寸
    cpuModel: '', // 机器信息-CPU型号
    batterySize: '', // 机器信息-电池容量

    colourIdB: '', // B端成色ID
    colourNameB: '', // B端成色Name
    colourId: '', // C端成色ID
    colourName: '' // C端成色Name
  };
  info: any;
  // 服务保障
  safeguardOptions = [];
  // 商品属性
  attrOptions = [];
  usedSwapList: any[] = [];
  // 设备基础信息
  deviceInfo: any;
  @ViewChild('reportModalRef') reportModalRef: any;

  // 利润 利润率
  profitObjs: any = {
    profitB: 0,
    profitRateB: 0,
    profitC: 0,
    profitRate: 0
  };

  // 改价Modal
  priceChangeVisible = false;

  constructor(
    private activatedRoute: ActivatedRoute,
    private usedStorePService: UsedStorePService,
    private nzMessageService: NzMessageService,
    public permissionService: PermissionService,
    private commonService: CommonService,
    private datePipe: DatePipe,
    private nzImageService: NzImageService
  ) {
  }

  ngOnInit(): void {
    this.initData();
    this.usedStorePService.swapListDictData().then((res: any) => {
      if (res.code === 0) {
        this.usedSwapList = JSON.parse(res.data.content);
      }
    });
  }

  initData() {
    // this.info = JSON.parse(this.activatedRoute.snapshot.queryParams.data);
    this.usedStorePService.getCommodityDetail(JSON.parse(this.activatedRoute.snapshot.queryParams.id)).then((res: any) => {
      if (res.code === 0) {
        const {recycleGoods, recycleMachine} = res.data || {};
        this.info = recycleGoods;
        this.deviceInfo = recycleGoods;

        this.getTypeOptions(); // 获取机型列表
        this.queryDictsData(); // 字典查询

        this.formData.title = recycleGoods.title || ''; // 商品名称
        this.formData.name = recycleGoods.name || ''; // 短标题
        this.formData.renewalFlag = recycleGoods.renewalFlag || 0; // 二手换机补贴标识

        this.formData.userType = this.info.userType;
        this.formData.shopPriceB = this.info.shopPriceB;
        this.formData.shopPriceC = this.info.shopPriceC;

        this.profitObjs.profitB = this.sumProfit(recycleGoods.shopPriceB, 1);
        this.profitObjs.profitRateB = this.sumProfit(recycleGoods.shopPriceB, 2);
        this.profitObjs.profitC = this.sumProfit(recycleGoods.shopPriceC, 1);
        this.profitObjs.profitRateC = this.sumProfit(recycleGoods.shopPriceC, 2);

        this.formData.imgs = this.info.imgs ? this.info.imgs.split(',') : [];
        this.formData.qualityResult = this.info.qualityResult;
        this.formData.asImg = this.info.asImg;
        const safeguardChecked = this.info.mallService.split(',');
        const attrChecked = this.info.properties.split(',');
        this.initOptions(safeguardChecked, attrChecked);

        this.formData.color = recycleGoods.color || ''; // 机器信息-颜色
        this.formData.network = recycleGoods.network || ''; // 机器信息-网络制式
        this.formData.version = recycleGoods.version || ''; // 机器信息-版本
        this.formData.isPrivateRepair = recycleGoods.isPrivateRepair; // 机器信息-私修痕迹 0无 1有
        this.formData.guaranteeTime = recycleGoods.guaranteeTime || ''; // 机器信息-保修截止日期
        this.formData.batteryHealth = recycleGoods.batteryHealth || ''; // 机器信息-电池健康值
        this.formData.chargeCount = recycleGoods.chargeCount || ''; // 机器信息-充电次数
        this.formData.imei = recycleGoods.imei || ''; // 机器信息-IMEI
        this.formData.screenSize = recycleGoods.screenSize || ''; // 机器信息-屏幕尺寸
        this.formData.cpuModel = recycleGoods.cpuModel || ''; // 机器信息-CPU型号
        this.formData.batterySize = recycleGoods.batterySize || ''; // 机器信息-电池容量

        this.formData.colourIdB = recycleGoods.colourIdB || ''; // B端成色ID
        this.formData.colourNameB = recycleGoods.colourNameB || ''; // B端成色Name
        this.formData.colourId = recycleGoods.colourId || ''; // C端成色ID
        this.formData.colourName = recycleGoods.colourName || ''; // C端成色Name
      }
    });
  }

  // 初始化选项
  initOptions(safeguardChecked: any[], attrChecked: any[]) {
    this.usedStorePService.dictData('es_service_guarantee').then((res: any) => {
      if (res.code === 0) {
        this.safeguardOptions = res.data.list.records.map((item: any) => ({
          ...item,
          label: item.name,
          value: item.content,
          checked: safeguardChecked.includes(item.content + '')
        }));
      }
    });
    this.usedStorePService.dictData('es_goods_attr').then((res: any) => {
      if (res.code === 0) {
        this.attrOptions = res.data.list.records.map((item: any) => ({
          ...item,
          label: item.name,
          value: item.content,
          checked: attrChecked.includes(item.content + '')
        }));
      }
    });
  }

  removeImg(index: any) {
    this.formData.imgs.splice(index, 1);
  }

  appendImg(url: any) {
    // @ts-ignore
    this.formData.imgs.push(url);
  }

  back() {
    window.history.go(-1);
  }

  save() {
    if (!this.formData.imgs?.length) {
      this.nzMessageService.error('请添加图片信息');
      return;
    }
    // 验证机器信息等
    if (!this.verifData()) {
      return;
    }
    // if (!this.formData.qualityResult) {
    //   this.nzMessageService.error('请输入质检结果');
    //   return;
    // }
    this.usedStorePService.updateCommodity({
      ...this.formData,
      guaranteeTime: this.formData.guaranteeTime ? this.datePipe.transform(this.formData.guaranteeTime, 'yyyy-MM-dd') : '',
      mallService: this.safeguardOptions.filter((i: any) => i.checked).map((i: any) => i.value).join(','),
      properties: this.attrOptions.filter((i: any) => i.checked).map((i: any) => i.value).join(','),
      imgs: this.formData.imgs.join(','),
      id: this.info.id,
      equipmentCode: this.info.equipmentCode,
    }).then(res => {
      if (res.code === 0) {
        this.nzMessageService.success('保存成功');
        // this.back();
        this.initData();
      }
    });
  }

  showReportModal(phoneCode: any) {
    const params = {
      phoneCode
    };
    this.reportModalRef.loadData(params);
    this.reportModalRef.isVisible = true;
  }

  showReportImg() {
    this.nzImageService.preview([{src: this.deviceInfo?.qualityResultImg}], {nzZoom: 1.5, nzRotate: 0});
  }

  /**
   * ----------------------------------------------------------------
   * 机器信息 2022/03/22
   * ----------------------------------------------------------------
   */
  colorOptions: any = []; // 颜色options
  networkOptions: any = [
    {value: '0', label: '全网通'},
    {value: '1', label: '双网通'},
    {value: '2', label: '移动版'},
    {value: '3', label: '联通版'},
    {value: '4', label: '电信版'},
    {value: '5', label: '不支持'},
    {value: '6', label: 'WiFi版'}
  ]; // 网络制式options
  editionOptions: any = [...purchaseChannelLists]; // 版本options
  batteryOptions: any = []; // 电池健康值options
  screenSizeOptions: any = []; // 屏幕尺寸options
  cpuOptions: any = []; // CPU型号options
  conditionBoptions: any = []; // B端成色options
  conditionCoptions: any = []; // C端成色options

  // 查询机型列表
  async getTypeOptions() {
    let params = {
      seriesId: this.deviceInfo.seriesId,
      page: 1,
      pageSize: 999999,
      source: 1
    };
    const res: any = await this.usedStorePService.queryModelList(params);
    if (res.code === 0) {
      const {records} = res.data || {};

      let tempObj: any = records.find((item: any) => item.id === this.deviceInfo.modelId);
      this.colorOptions = tempObj?.color ? tempObj?.color.split(',') : [];
    }
  }

  // 查询字典
  async queryDictsData() {
    // 电池健康值options
    this.batteryOptions = await this.commonService.getDictList('es_battery_health');
    // 屏幕尺寸options
    this.screenSizeOptions = await this.commonService.getDictList('phone_screen_size');
    // CPU型号options
    this.cpuOptions = await this.commonService.getDictList('phone_cpu_model');
    // B端成色options
    this.conditionBoptions = await this.commonService.getDictList('machine_condition_b');
    // C端成色options
    this.conditionCoptions = await this.commonService.getDictList('machine_condition');
  }

  // 成色选择change
  conditionChange(value: any, str: string) {
    let tmpArrs = (str.toLocaleUpperCase() === 'C' ? this.conditionCoptions : this.conditionBoptions) || [];
    let obj: any = tmpArrs.find((item: any) => item.id == value);
    switch (str.toLocaleUpperCase()) {
      case 'C':
        this.formData.colourName = obj?.name || '';
        return;
      case 'B':
        this.formData.colourNameB = obj?.name || '';
        return;
    }
  }

  // 验证机器信息等...
  verifData() {
    let verifArrs: any = [
      {key: 'color', tip: '请选择机器颜色'},
      {key: 'network', tip: '请选择机器网络制式'},
      {key: 'version', tip: '请选择机器版本'},
      {key: 'imei', tip: '请输入机器IMEI'},
      // { key: 'isPrivateRepair', tip: '请选择机器有无私修痕迹' },
      // { key: 'guaranteeTime', tip: '请选择机器保修截止日期' },
      // { key: 'batteryHealth', tip: '请选择机器电池健康值' },
      // { key: 'chargeCount', tip: '请输入机器充电次数' },
      // { key: 'screenSize', tip: '请选择机器屏幕尺寸' },
      // { key: 'cpuModel', tip: '请选择机器CPU型号' },
      // { key: 'batterySize', tip: '请输入机器电池容量' },
      {key: 'colourIdB', tip: '请选择B端成色'},
      {key: 'colourId', tip: '请选择C端成色'}
    ];
    let tempBool = false;

    for (let i = 0; i < verifArrs.length; i++) {
      let obj = verifArrs[i];
      if (!this.isVerifPass(this.formData[obj.key])) {
        this.nzMessageService.warning(obj.tip);
        tempBool = false;
        return;
      } else {
        tempBool = true;
      }
    }
    return tempBool;
  }

  isVerifPass(val: any) {
    if (val === '' || val === undefined || val === null) {
      return false;
    } else {
      return true;
    }
  }

  // 建议零售价 (成交价 + 60） * 1.1) + 加价值
  sumRetailPrice(val: any) {
    let sum = 0;
    sum = Math.ceil(((this.deviceInfo?.realValuation || 0) + (this.deviceInfo?.aprc || 0) + (this.deviceInfo?.cprc || 0) + 60) * val);
    return sum;
  }

  /**
   * type 1：利润 2：利润率
   * 利润：输入的值 - (输入的值 / 1.03 * 0.03) - (输入的值 / 1.03 * 0.03) * 0.12  - (输入的值 * 0.006) - 成交价 - 60
   * 利润率：利润 / (成交价 + 60 + (输入的值 / 1.03 * 0.03) * 0.12  + 输入的值 * 0.006) 1.1289
   * 注：成交价 = realValuation + aprc
   */
  sumProfit(val: any, type: number) {
    let baseVal = val || 0;
    let prifitTotal = 0;
    let prifitRate = 0;
    let transactionPrice = (this.deviceInfo?.realValuation || 0) + (this.deviceInfo?.aprc || 0) + (this.deviceInfo?.cprc || 0); // 成交价

    prifitTotal = baseVal - (baseVal / 1.03 * 0.03) - (baseVal / 1.03 * 0.03 * 0.12) - (baseVal * 0.006) - (transactionPrice || 0) - 60;
    prifitRate = prifitTotal / ((transactionPrice || 0) + 60 + (baseVal / 1.03 * 0.03 * 0.12) + (baseVal * 0.006));

    return type === 1 ? prifitTotal.toFixed(2) : (prifitRate * 100).toFixed(2);
  }

  priceChange(event: any, type: string) {
    if (type === 'b') {
      this.profitObjs.profitB = this.sumProfit(event, 1);
      this.profitObjs.profitRateB = this.sumProfit(event, 2);
    } else {
      this.profitObjs.profitC = this.sumProfit(event, 1);
      this.profitObjs.profitRateC = this.sumProfit(event, 2);
    }
  }
}
